package cn.kelvin.stack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;

public class MyStack<T> {
	Object[] datas = {};
	int size;
	int top=0;
	
	public MyStack() {
	}
	
	public MyStack(int size){
		this.size = size;
		datas = new Object[size];
	}
	
	public void push(T t){
		ensureCapacity(top);
		datas[top++] = (Object) t;
	}
	
	private void ensureCapacity(int newSize) {
		if(newSize>=size){
			size = (int)(Math.round(size + size*1.5+1));
//			System.out.println("add->"+size);
			datas = Arrays.copyOf(datas,size);
		}
	}

	@SuppressWarnings("unchecked")
	public T pop(){
		if(top<=size && top>0){
			return (T) datas[--top];
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public T getTop(){
		int n = top - 1;
		if(n<size && n>=0){
			return (T) datas[n];
		}
		return null;
	}
	
	public int size(){
		return top;
	}
	
	public boolean isEmpty(){
		return top==0;
	}
	
	public static void main(String[] args) {
//		int n = (int)(Math.round(1 + 1*1.5));
//		System.out.println(n);
		
		MyStack<String> stack = new MyStack<>(1);
		stack.push("aaa");
		stack.push("bbb");
		stack.push("ccc");
//		stack.push("ddd");
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println(stack.getTop());
		System.out.println(stack.size());
	}
}
